import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/login_info_entity.dart';
import 'package:seedfour/app/models/sms_entity.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../remote/request.dart';
import '../../services/api_service.dart';
import '../web_screen/screen_params.dart';

class LoginSmsLogic extends GetxController {
  var phoneController = TextEditingController().obs;
  var codeController = TextEditingController().obs;
  var isLoading = false.obs;
  var countdown = 60.obs;
  var isSending = false.obs;
  var isAgree = false.obs;

  final agreementUrl = 'https://api.seedfour.com/res/api/v1/user/agreement';
  final privacyUrl = 'https://api.seedfour.com/res/api/v1/user/privacy';

  final ApiService apiService = Get.find();

  Timer? _timer;

  void startCountdown() {
    countdown.value = 60;
    isSending.value = true;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdown.value--;
      if (countdown.value <= 0) {
        isSending.value = false;
        _timer?.cancel();
      }
    });
  }

  void getSmsCode() => request(
        () async {
          if (isAgree.value == false) {
            Get.snackbar('提示', '请先阅读并同意用户协议');
            return;
          }

          String mobile = phoneController.value.value.text;
          startCountdown();

          SmsEntity? result = await apiService.sendSms(mobile);
          if (result != null) {
            Get.snackbar('提示', '短信已经下发，${result.ttlDesc}内有效');
          }
        },
        showLoading: true,
      );

  void login() => request(
        () async {
          String mobile = phoneController.value.value.text;
          String smsCode = codeController.value.value.text;

          if (isAgree.value == false) {
            Get.snackbar('提示', '请先阅读并同意用户协议');
            return;
          }

          if (mobile.isEmpty || smsCode.isEmpty) {
            Get.snackbar('提示', '请输入手机号和验证码');
            return;
          }

          isLoading.value = true;

          LoginInfoEntity? result = await apiService.smsLogin(mobile, smsCode);
          isLoading.value = false;
          if (result != null) {
            _loginSuccess();
          }
        },
        showLoading: true,
      );

  void onClickAgreement() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: agreementUrl));
  }

  void onClickPrivacy() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: privacyUrl));
  }

  void _loginSuccess() {
    apiService.getUserInfo().then((value) {
      isLoading.value = false;
      if (value != null) {
        Get.snackbar('提示', '登录成功');
        Get.offAllNamed(RouteGet.main);
      }
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }
}
